//
//  XFDraggableView.m
//  FreeTime
//
//  Created by 王江华 on 16/8/26.
//  Copyright © 2016年 SRDZ.com. All rights reserved.
//

#import "XFDraggableView.h"

#import "SDWebImageManager.h"
#import "FileUnit.h"
#import "Header.h"

#import "XFCameraView.h"



#define OVERLAYWIDTH 80.0f
#define ACTION_MARGIN 50
#define SCALE_STRENGTH 4
#define SCALE_MAX .93
#define ROTATION_MAX 1
#define ROTATION_STRENGTH WindowWidth
#define ROTATION_ANGLE M_PI/10
#define NAMELABEL_HEIGHT 20
#define DISTANCE_HEIGHT 20
#define NATURE_HEIGHT 40
#define ANIMATION_TIME 0.5f
#define MUSIC @"火花.mp3"

@interface XFDraggableView()<SDWebImageManagerDelegate>

{
    CGFloat _xFromCenter;
    CGFloat _yFormCenter;
    NSInteger _currentTime;
}
@property(nonatomic,strong)UIImageView *headImageView;
@property(nonatomic,strong)UILabel *nameLabel;
@property(nonatomic,strong)UILabel *distanceLabel;
@property(nonatomic,strong)UIPanGestureRecognizer *panGesture;
@property(nonatomic)CGPoint originalPoint;
@property(nonatomic,strong)UIImageView *natureImageView;
@property(nonatomic,strong)UILabel *regainLabel;
@property(nonatomic,strong) XFCameraView*cameraView;
@property(nonatomic,strong)MWMainUserModel *model;
@property(nonatomic,strong)FileUnit *fileUnit;

@end
@implementation XFDraggableView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self setupView];
        //头像
        if (!_headImageView) {
            _headImageView = [[UIImageView alloc] init];
            [self addSubview:_headImageView];
            _headImageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageAction:)];
            tap.numberOfTapsRequired = 1;
            tap.numberOfTouchesRequired = 1;
            [_headImageView addGestureRecognizer:tap];
        }
        if (!_regainLabel) {
            _regainLabel = [[UILabel alloc] init];
            _regainLabel.layer.cornerRadius = 5.0f;
            _regainLabel.clipsToBounds = YES;
            _regainLabel.layer.borderColor = TEXTCOLOR.CGColor;
            _regainLabel.layer.borderWidth = 1.0f;
            _regainLabel.textColor = TEXTCOLOR;
            _regainLabel.textAlignment = NSTextAlignmentCenter;
            _regainLabel.font = [UIFont systemFontOfSize:13.0f];
            [self addSubview:_regainLabel];
        }
        if (!_heartImageView) {
            _heartImageView = [[UIImageView alloc] init];
            _heartImageView.alpha = 0.7f;
            _heartImageView.image = [UIImage imageNamed:@"meng"];
            [_headImageView addSubview:_heartImageView];
        }
        //姓名 年龄
        if (!_nameLabel) {
            _nameLabel = [[UILabel alloc] init];
            _nameLabel.font = [UIFont systemFontOfSize:12.0f];
            _nameLabel.textColor = TEXTCOLOR;
            [self addSubview:_nameLabel];
        }
        //距离
        if (!_distanceLabel) {
            _distanceLabel = [[UILabel alloc] init];
            _distanceLabel.font = [UIFont systemFontOfSize:12.0f];
            _distanceLabel.textColor = TEXTCOLOR;
            [self addSubview:_distanceLabel];
        }
        if (!_cameraView) {
            _cameraView = [[XFCameraView alloc] init];
            [self addSubview:_cameraView];
        }
        //对错
        if (!_overlayView) {
            _overlayView = [[XFOverlayView alloc] init];
            [self addSubview:_overlayView];
        }
        //类型
        if (!_natureImageView) {
            _natureImageView = [[UIImageView alloc] init];
            [self addSubview:_natureImageView];
        }
        
        _currentTime = 0;
        _panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
        [self addGestureRecognizer:_panGesture];
        
        self.frame = frame;
    }
    return self;
}

-(FileUnit *)fileUnit
{
    if (!_fileUnit) {
        _fileUnit = [FileUnit shareInstance];
    }
    return _fileUnit;
}

#pragma mark -设置阴影
-(void)setupView
{
    self.layer.cornerRadius = 4;
    self.layer.shadowRadius = 3;
    self.layer.shadowOpacity = 0.2;
    self.layer.shadowOffset = CGSizeMake(1, 1);
}


#pragma mark -panGesture
-(void)panAction:(UIPanGestureRecognizer *)pan
{
    _xFromCenter = [pan translationInView:self].x;
    _yFormCenter = [pan translationInView:self].y;
    
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:{
            self.originalPoint = self.center;
            self.layer.shouldRasterize = YES;
        }
            break;
        case UIGestureRecognizerStateChanged:{
            
            CGFloat rotationStrength = MIN(_xFromCenter/self.frame.size.width,ROTATION_MAX);
            CGFloat rotationAngel = (CGFloat)(ROTATION_ANGLE * rotationStrength);
            CGFloat scaleStrength = 1 - (1- SCALE_MAX) * fabs(rotationStrength);
            CGFloat scale = MAX(scaleStrength, SCALE_MAX);
            self.center = CGPointMake(self.originalPoint.x + _xFromCenter, self.originalPoint.y+_yFormCenter);
            CGAffineTransform transForm = CGAffineTransformMakeRotation(rotationAngel);
            CGAffineTransform scaleTransForm = CGAffineTransformScale(transForm, scale, scale);
            
            self.transform = scaleTransForm;
            [self updateOverlay:_xFromCenter];
        }
            break;
        case UIGestureRecognizerStateEnded:{
            [self afterSwipeAction];
        }
            break;
        case UIGestureRecognizerStatePossible:break;
        case UIGestureRecognizerStateCancelled:break;
        case UIGestureRecognizerStateFailed:break;
            
        default:
            break;
    }
}


-(void)updateOverlay:(CGFloat)xFormCenter
{
    if (xFormCenter > 0) {
        _overlayView.mode = CGOverlayViewModeRight;
        CGRect frame = _overlayView.frame;
        frame.origin.x = 10;
        frame.origin.y = 10;
        _overlayView.frame = frame;
    }else{
        _overlayView.mode = CGOverlayViewModeLeft;
        CGRect frame = _overlayView.frame;
        frame.origin.x = _heartImageView.frame.size.width - OVERLAYWIDTH - 10;
        frame.origin.y = 10;
        _overlayView.frame = frame;
    }
    _overlayView.alpha = MIN(fabs(xFormCenter)/(self.frame.size.width / 2), 1);
}

//不触摸
-(void)afterSwipeAction
{
    if (_xFromCenter > ACTION_MARGIN) {
        [self rightAction];
    }else if (_xFromCenter < - ACTION_MARGIN){
        [self leftAction];
    }else{
        [UIView animateWithDuration:ANIMATION_TIME
                              delay:0
             usingSpringWithDamping:0.5
              initialSpringVelocity:2.0f
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             self.center = self.originalPoint;
                             self.transform = CGAffineTransformMakeRotation(0);
                             _overlayView.alpha = 0;
                             self.layer.shouldRasterize = NO;
                             return;
                         } completion:^(BOOL finished) {
                             self.transform = CGAffineTransformIdentity;
                             return;
                         }];
        
    }
}

-(void)rightAction
{
    CGPoint finishPoint = CGPointMake(WindowWidth * 2, 2*_yFormCenter +self.originalPoint.y);
    [UIView animateWithDuration:ANIMATION_TIME
                          delay:0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         self.center = finishPoint;
                     } completion:^(BOOL finished) {
                         [self removeFromSuperview];
                     }];
    [self.delegate cardSwipedRight:self];
}



-(void)leftAction
{
    CGPoint finishPoint = CGPointMake(-500, 2*_yFormCenter +self.originalPoint.y);
    [UIView animateWithDuration:ANIMATION_TIME
                          delay:0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         self.center = finishPoint;
                     } completion:^(BOOL finished) {
                         [self removeFromSuperview];
                     }];
    
    [self.delegate cardSwipedLeft:self];
}

-(void)rightClickAction
{
    CGPoint finishPoint = CGPointMake(800, self.center.y);
    [UIView animateWithDuration:ANIMATION_TIME
                     animations:^{
                         
                         self.center = finishPoint;
                         //设置转向
                         self.transform = CGAffineTransformMakeRotation(1);
                     }completion:^(BOOL complete){
                         
                         [self removeFromSuperview];
                     }];
    [self.delegate cardSwipedRight:self];
}

-(void)leftClickAction
{
    CGPoint finishPoint = CGPointMake(-800, self.center.y);
    [UIView animateWithDuration:ANIMATION_TIME
                     animations:^{
                         self.center = finishPoint;
                         self.transform = CGAffineTransformMakeRotation(-1);
                     }completion:^(BOOL complete){
                         [self removeFromSuperview];
                     }];
    
    [self.delegate cardSwipedLeft:self];
}

-(void)imageAction:(UITapGestureRecognizer *)tap
{
    if ([self.delegate respondsToSelector:@selector(cardView:didselectHeadImageWithId:)]) {
        [self.delegate cardView:self didselectHeadImageWithId:self.model.targetUserId];
    }
}

-(void)dealloc
{
    [_headImageView removeFromSuperview];
    [_natureImageView removeFromSuperview];
    [_heartImageView removeFromSuperview];
    [_nameLabel removeFromSuperview];
    [_distanceLabel removeFromSuperview];
    [_cameraView removeFromSuperview];
    [_overlayView removeFromSuperview];
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    CGRect imageFrame = _headImageView.frame;
    imageFrame.size.width = self.frame.size.width;
    if (WindowHeight <= 480) {
        imageFrame.size.height = self.frame.size.height - 40;
    }else{
        imageFrame.size.height = self.frame.size.width;
    }
    //背景图片
    _headImageView.frame = imageFrame;
    //蒙版
    _heartImageView.frame = _headImageView.bounds;
    //不小心错过
    //    _regainImageView.frame = CGRectMake(_heartImageView.frame.size.width - 90, _heartImageView.frame.size.height - 65, 85, 60);
    //类型
    _natureImageView.frame = CGRectMake(5, _heartImageView.frame.size.height-NATURE_HEIGHT-5 , NATURE_HEIGHT, NATURE_HEIGHT);
    
    CGFloat width = self.frame.size.width / 3;
    //名字
    _nameLabel.frame = CGRectMake(10, (self.frame.size.height-CGRectGetMaxY(_headImageView.frame) - DISTANCE_HEIGHT - NAMELABEL_HEIGHT)/2+CGRectGetMaxY(_headImageView.frame), width-10, NAMELABEL_HEIGHT);
    
    //喜欢未配对
    _regainLabel.frame = CGRectMake(width + 10, CGRectGetMaxY(_headImageView.frame) + 10, width - 20, self.frame.size.height - CGRectGetMaxY(_headImageView.frame) - 20 );
    
    //距离
    _distanceLabel.frame = CGRectMake(_nameLabel.frame.origin.x, CGRectGetMaxY(_nameLabel.frame), width-10, DISTANCE_HEIGHT);
    _distanceLabel.adjustsFontSizeToFitWidth = YES;
    
    //相机
    _cameraView.frame = CGRectMake(2*width, (self.frame.size.height-CGRectGetMaxY(_headImageView.frame)-25)/2+CGRectGetMaxY(_headImageView.frame), width, 20);
    
    _overlayView.frame = CGRectMake(self.center.x - OVERLAYWIDTH / 2, 10, OVERLAYWIDTH, OVERLAYWIDTH);
}



-(void)setDraggalbleViewWithModel:(MWMainUserModel *)model
{
    self.model = model;
    //设置蒙版
    _regainLabel.hidden = YES;
    if (model.regainStatus.length > 0) {
        if ([model.regainStatus integerValue] == 0) {
            _heartImageView.image = [UIImage imageNamed:@"meng_unlike"];
        }else{
            _regainLabel.hidden = NO;
            _regainLabel.text = @"喜欢但未配对";
            _heartImageView.image = [UIImage imageNamed:@"meng_like"];
        }
    }
    
    //设置背景图片
    //    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:model.headImg] options:SDWebImageCacheMemoryOnly progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    //    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
    //        _headImageView.image = [self changeImage:image];
    //    }];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"QDLOGO@2x" ofType:@"png"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    _headImageView.image = [UIImage imageWithData:data];
    
    //    [_headImageView sd_setImageWithURL:[NSURL URLWithString:model.headImg] placeholderImage:[UIImage imageWithData:data] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    //        _headImageView.image = [self changeImage:image];
    //    }];
    if (model.headImg.length > 0 && ![model.headImg isEqualToString:@"(null)"] && ![model.headImg isEqualToString:@""]) {
        NSURL *imageUrl = [NSURL URLWithString:model.headImg];
        if ([self.fileUnit hasCachedImage:imageUrl]) {
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[self.fileUnit pathForUrl:imageUrl]]];
            _headImageView.image = [self changeImage:image];
        }else{
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:imageUrl,@"URL",self.headImageView,@"imageView", nil];
            [NSThread detachNewThreadSelector:@selector(cacheImage:) toTarget:self withObject:dict];
        }
    }
   /*NSString *close = [[NSUserDefaults standardUserDefaults] objectForKey:MW_CLOSEPRICE];
    if ([close integerValue] == 0) {
        //设置视频认证
        if (model.videoImg.length > 0) {
            model.headImg = model.videoImg;
            UIImageView *videoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
            videoImageView.image = [UIImage imageNamed:@"shenfenyirenzheng"];
            [self.headImageView addSubview:videoImageView];
        }
    }*/
    
    
    //设置姓名
    _nameLabel.text =[NSString stringWithFormat:@"%@,%@",model.nickName,model.sex];
    
    
    //设置距离
    NSString *distance;
    distance = @"";
    if (model.city.length > 0 && ![model.city isEqualToString:@"(null)"]) {
        distance = model.city;
    }
    if (model.locationDesc.length && ![model.locationDesc isEqualToString:@"(null)"]) {
        distance = model.locationDesc;
    }
    if (model.latitude.length > 0 && model.longitude.length > 0) {
        //distance = [NSString stringWithFormat:@"%@(%@)",distance,[MapTool getFiterWithLatitude:[model.latitude floatValue] longitude:[model.longitude floatValue]]];
        _distanceLabel.text = distance;
    }
    
    //设置照片数量
    _cameraView.photos = [NSString stringWithFormat:@"%li",model.headAlbum.count];
    _overlayView.alpha = 0;
    
    //设置类型
    NSArray *titleArray = @[@"无私者",@"友好者",@"诚实者",@"博学者",@"无畏者"];
    NSArray *imageArray=@[@"wusizhe_1",@"hepingzhe_1",@"chengshizhe_1",@"zhihuizhe_1",@"wuweizhe_1"];
    if (model.nature.length > 0 && ![model.nature isEqualToString:@"<null>"]) {
        for (int i =0; i<5; i++) {
            if ([model.nature isEqualToString:titleArray[i]]) {
                _natureImageView.image = [UIImage imageNamed:imageArray[i]];
                break;
            }
        }
    }
    
}

#pragma mark - 图片缓存
-(void)cacheImage:(NSDictionary *)dic{
    NSURL *url = dic[@"URL"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSString *fileName = [self.fileUnit pathForUrl:url];
    if (data) {
        [fileManager createFileAtPath:fileName contents:data attributes:nil];
        [self performSelectorOnMainThread:@selector(haveDownImage:) withObject:data waitUntilDone:YES];
    }else{
       
    }
}

-(void)haveDownImage:(NSData *)imageData
{
    self.headImageView.image = [self changeImage:[UIImage imageWithData:imageData]];
}
//-(UIImage*) circleImage:(UIImage*) image withParam:(CGFloat) inset {
//    UIGraphicsBeginImageContext(image.size);
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextSetLineWidth(context, 2);
//    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
//    CGRect rect = CGRectMake(inset, inset, image.size.width - inset * 2.0f, image.size.height - inset * 2.0f);
//    CGContextAddEllipseInRect(context, rect);
//
//    CGContextClip(context);
//
//    [image drawInRect:rect];
//    CGContextAddEllipseInRect(context, rect);
//    CGContextStrokePath(context);
//    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return newimg;
//}

- (UIImage *)changeImage:(UIImage *)image
{
    //裁剪图片
    if (image.size.height > image.size.width) {
        CGRect rect = CGRectMake(0, (image.size.height - image.size.width)/2, image.size.width, image.size.width);
        CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
        image = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);
        return image;
    }else{
        CGRect rect = CGRectMake((image.size.width - image.size.height) / 2, 0, image.size.height, image.size.height);
        CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
        image = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);
        return image;
    }
}







@end
